package com.cykj.chat.schedule;

import com.cykj.chat.mapper.ChatMapper;
import com.cykj.common.entity.ChatRecordDO;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * @BelongsProject: smart_recruit_backend
 * @BelongsPackage: com.cykj.chat.schedule
 * @Author: 蔡张君逸
 * @CreateTime: 2025-08-25 20:29
 * @Description: TODO
 * @Version: 1.0
 */
//把redis聊天记录同步到数据库的定时器
@Component
public class writeSchedule {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    ChatMapper chatMapper;

//    定时触发单位是毫秒
    @Scheduled(fixedRate = 5000)
    public void writeMsg() {
        Set<String> keys = redisTemplate.keys("records:*");
        if (keys!=null) {
            for (String key : keys) {
                List<ChatRecordDO> chatList = objectMapper.convertValue(redisTemplate.opsForValue().get(key), new TypeReference<List<ChatRecordDO>>() {});
                for (ChatRecordDO chatRecordDO : chatList) {
                    if (chatRecordDO.getRecordId()==null) {
                        int res = chatMapper.addRecord(chatRecordDO);
//                        这边的recordId是随便给一个值，让它不再触发插入就行
                    }
                }
                redisTemplate.opsForValue().set(key, chatList);
            }
        }

    }

}